﻿
using AppSocketModel;
using AppSocketService.Relay;
using BCGPSCommon;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace AppSocketControl.Relay
{
    /// <summary>
    /// 数据转发服务
    /// </summary>
    public class RelayServer
    {
        private static RelayServer staticRelayServer ;
        private readonly IRelayService relayService;
        private Thread thread=null;

        public RelayServer()
        { 
            this.relayService = new RelayService();
            staticRelayServer = this;
        }

        public static RelayServer GetRelayServer()
        {
            return staticRelayServer;
        }

        public void Run()
        {
            RelayDeviceDictionary.ImeiDict.Clear();

            thread = new Thread(ListenCmd);
            thread.Start();
        }
        

        //等待新的命令下发
        //停止命令: 移除字典中对应公司下IMEI.
        //启动命令:将对应公司中的IMEI添加到字典.
        public void ListenCmd()
        {
            var listall = relayService.GetAll();
            foreach (var item in listall)
            {
                if(item.RelayServerRunState == RelayServerRunState.RUN && item.RelayControlCmdState == RelayControlCmdState.COMPLETE)
                {
                    RelayDeviceDictionary.Reset(item);
                }
            }
            while(true)
            {
                //
                var list = relayService.GetNewCommond(); 

                foreach (var item in list)
                {
                    Msg.WirteLine($"有新的控制命令下发CompanyId:={item.CompanyId} , 要修改服务状态:={item.RelayServerRunState.ToString()}", 0);

                    if (item.RelayServerRunState == RelayServerRunState.RUN)
                    {
                        RelayDeviceDictionary.Reset(item);
                        relayService.SetCmdRunState(item.CompanyId, RelayControlCmdState.RUNNING);
                    }
                    else if (item.RelayServerRunState == RelayServerRunState.STOP)
                    {
                        RelayDeviceDictionary.ClearDict(item.CompanyId);
                        relayService.SetCmdRunState(item.CompanyId, RelayControlCmdState.RUNNING);
                    }
                }
                Thread.Sleep(1000);
                
            }
        }

    }
} 